

const PENDING = "PENDING"
const FULFILLED = "FULFILLED"
const REJECTED = "REJECTED"

class Promise {
  constructor(executor) {
    this.status = PENDING
    // 成功值
    this.value = undefined
    // 失败值
    this.reason = undefined
    // 解决异步调用问题
    this.onFulfilledCallback = []
    this.onRejectedCallback = []

    let resolve = (value) => {
      if(this.status == PENDING) {
        console.log('我是resolve')
        this.status = FULFILLED
        this.value = value
        this.onFulfilledCallback.forEach(fn => fn())
      }
    }

    let rejected = (reason) => {
      if(this.status == PENDING) {
        this.status = REJECTED
        this.reason = reason
        this.onRejectedCallback.forEach(fn => fn())
      }
    }

    // Promise构造函数执行时立即调用executor 函数 resolve 和 reject 函数被调用时，分别将promise的状态改为fulfilled（完成）或rejected（失败）。
    try {
      executor(resolve)
    } catch(err) {
      executor(rejected)
    }
  }

  // 解决(fulfillment)和拒绝(rejection)回调到当前 promise, 返回一个新的 promise, 将以回调的返回值来resolve.
  then(onFulfilled, onRejected) {
    console.log('是否执行了', this.status)
    if(this.status == FULFILLED) {
      onFulfilled(this.value)
    }

    if(this.status == REJECTED) {
      onRejected(this.reason)
    }

    if(this.status == PENDING) {
      this.onFulfilledCallback.push(()=>{
        onFulfilled(this.value)
      })

      this.onRejectedCallback.push(()=>{
        onRejected(this.reason)
      })
    }
  }
}


let p1 = new Promise((resolve, reject)=>{
  setTimeout(() => {
    resolve("1233")
  }, 1000)
 
})

p1.then((data) => {
  console.log(data)
}, (err) => {
  console.log(err)
})